import {
	tips
} from '@/utils/util.js'
import {
	http
} from '@/utils/commonRequest.js'; // 局部引入
import {checkAuth} from '../check.js'

/**
 * 领取线下优惠券
 */
function getOfflineCoupon(couponId) {
	uni.navigateTo({
		url: '/pages/coupon/couponDetail/couponDetail?couponId=' + couponId,
	})
}

/**
 * 领取线上平台优惠券或者领取线上商户优惠券
 * @param {*} couponid 优惠券id
 * @param {*} cardFlag 是否开通微信卡券：0-未开通 1-已开通
 * @param {*} type 优惠券类型：Merchant-商户券 Plat-平台券
 */
function getOnlineCoupon(couponid, cardFlag = "0", type) {
	checkAuth().then(res => {
		if ('authed' == res) {
			uni.showLoading({
				title: '领取中',
			})
			let params = {
				'couponId': couponid
			}
			if ("0" === cardFlag) {
				http.post("shop/getCoupon", {
					'couponid': couponid,
					'couponType': type
				}, {
					header: {
						"content-type": "application/x-www-form-urlencoded"
					}
				}).then(res => {
					uni.hideLoading()
					res = res.data
					if (200 == res.code) {
						showToast(res)
					} else if (500 == res.code) {
						tips(res.msg)
					}
				}).catch(err => {
					uni.hideLoading()
					tips("领取失败，请稍后再试")
				})
			} else if ("1" === cardFlag) {
				//先调用微信接口获取微信随机分配的code（先判断该用户是否领过卡券），用户领取成功后再更新我们系统的券码
				http.get("shop/hasCoupon", {
					params: params
				}).then(res => {
					res = res.data
					let flag = res.flag;
					if (!flag) {
						uni.hideLoading()
						tips('参数异常')
						return;
					}
					if ("1" == flag) {
						uni.hideLoading()
						tips('已经领取过该优惠券，不能重复领取')
						return;
					} else if ("0" == flag) {
						//调用微信卡券接口获取导入的一张code,先获取签名参数
						http.get("member/getCouponParam", {
							params: params
						}).then(res1 => {
							res1 = res1.data
							let code = res1.code;
							if (200 !== code) {
								uni.hideLoading()
								tips('获取微信参数异常！')
								return;
							} else {
								uni.addCard({
									cardList: [{
										cardId: res1.cardId,
										cardExt: '{"outer_str":"miniProgram","timestamp":"' +
											res1.timestamp +
											'","nonce_str":"' + res1.nonceStr +
											'","signature":"' + res1
											.signature + '"}'
									}], // 需要添加的卡券列表
									success: function(res2) {
										let cardList = res2.cardList;
										console.log("cardList-----" + cardList);
										let obj = cardList[0];
										console.log("obj-----" + obj);
										let encryptCode = obj.code;
										console.log("encryptCode-----" +
											encryptCode);
										let cardId = obj.cardId;
										console.log("cardId-----" + cardId);
										//通过获取的code从我们数据库中找出对应的code并更新用户信息
										http.post("shop/getCouponNew", {
											'couponid': couponid,
											'encryptCode': encryptCode,
											'cardId': cardId
										}, {
											header: {
												"content-type": "application/x-www-form-urlencoded"
											}
										}).then(res3 => {
											res3 = res3.data
											uni.hideLoading()
											if (200 == res3.code) {
												showToast(res)
											}
										})
									}
								})
							}
						}).catch(err => {
							uni.hideLoading()
							tips("领取失败，请稍后再试")
						})
					}
				})
			}
		}
	});
}

function showToast(res) {
	if (res.msg == "SUCCESS" && res.noEffTimes == "No" && res.noLimitTimes == "No") {
		uni.showToast({
			title: "领取成功"
		})
	} else if (res.msg == "SUCCESS" && res.noEffTimes == "Yes") {
		uni.showToast({
			title: "领取成功"
		})
	} else if (res.msg == "SUCCESS" && res.noEffTimes == "No" && res.noLimitTimes != "No") {
		uni.showToast({
			title: "领取成功"
		})
	} else if (res.msg == "NO_COUPONS") {
		tips('很抱歉，该优惠券已领完"')
	} else if (res.msg == "NO_EFFLIMIT_TIMES") {
		tips('很抱歉，领券次数用完！"')
	} else if (res.msg == "NO_PERLIMIT_TIMES") {
		tips('很抱歉，周期内领取已达上限"')
	} else if (res.msg == "SUCCESS") {
		uni.showToast({
			title: "领取成功"
		})
	}
	if (res.msg == "SUCCESS") {
		setTimeout(() => {
			uni.navigateTo({
				url: '/subPackages/minorPkg/pages/coupon/myCoupon',
			})
		}, 1500);
	}
}

module.exports = {
	getOnlineCoupon: getOnlineCoupon,
	getOfflineCoupon: getOfflineCoupon
}
